﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace EFFC.Net.Common
{
    public class ComFunc
    {
        [DllImport("kernel32.dll")]
        public static extern bool SetProcessWorkingSetSize(IntPtr handle,
                     int minimumWorkingSetSize, int maximumWorkingSetSize);

        /// <summary>
        /// 字符串的Null處理，并作Trim處理
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string nvl(object obj)
        {
            if (obj == null)
            {
                return "";
            }
            else
            {
                return obj.ToString().ToString().Trim();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string FindFileName(string s)
        {
            string filereg = @"[a-zA-Z _0-9]+(.[a-zA-Z]+)?$";
            Regex reg = new Regex(filereg);
            return reg.Match(s).Value; ;
        }

        
        /// <summary>
        /// string數組轉化ArrayList
        /// </summary>
        /// <param name="strs"></param>
        /// <returns></returns>
        public static ArrayList StringArrayToArrayList(string[] strs)
        {
            ArrayList rtn = new ArrayList();
            for (int i = 0; strs != null && i < strs.Length; i++)
            {
                rtn.Add(strs[i]);
            }

            return rtn;
        }
        /// <summary>
        /// 返回指定長度的隨機數
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static int Random(int length)
        {
            string l = "1";
            for (int i = 0; i < length; i++)
            {
                l += "0";
            }
            Random r = new Random();
            return r.Next(int.Parse(l));
        }

        /// <summary>
        /// 調用Exe程序
        /// </summary>
        /// <param name="exepath"></param>
        /// <returns></returns>
        public static bool CallExe(string exepath, List<string> parameters)
        {
            try
            {
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo.FileName = exepath;

                string paramstr = "";
                for (int i = 0; parameters != null && i < parameters.Count; i++)
                {
                    paramstr += " " + parameters[i];
                }

                proc.StartInfo.Arguments = " " + paramstr;
                string skd = "";
                proc.StartInfo.UseShellExecute = false;             
                proc.StartInfo.RedirectStandardInput = true;        
                proc.StartInfo.RedirectStandardOutput = true;       
                proc.StartInfo.RedirectStandardError = true;        
                proc.StartInfo.CreateNoWindow = false;

                if (proc.Start())
                {

                    proc.WaitForExit();
                    skd = proc.StandardOutput.ReadToEnd();
                    proc.Close();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 將字符串轉換成對應的Enum類型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="s"></param>
        /// <returns></returns>
        public static T EnumParse<T>(string s)
        {
            return (T)Enum.Parse(typeof(T), s);
        }

        public static string MergeScript(string firstScript, string secondScript)
        {
            if (!string.IsNullOrEmpty(firstScript))
            {
                return (firstScript + secondScript);
            }
            if (secondScript.TrimStart(new char[0]).StartsWith("javascript:", StringComparison.Ordinal))
            {
                return secondScript;
            }
            return ("javascript:" + secondScript);
        }

        public static string EnsureEndWithSemiColon(string value)
        {
            if (value != null)
            {
                int length = value.Length;
                if ((length > 0) && (value[length - 1] != ';'))
                {
                    return (value + ";");
                }
            }
            return value;
        }
        /// <summary>
        ///強制清理內存，慎用，適用於win32NT平臺
        /// </summary>
        public static void MemoryCollect()
        {
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
            }
        }

        /// <summary>
        ///判斷是否為中文
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsChineseString(string str)
        {
            return Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(str)) != str;
        }
        /// <summary>
        /// 將字符串從一種編碼轉變成另一種編碼
        /// </summary>
        /// <param name="str">待轉換的字符串</param>
        /// <param name="from">原編碼</param>
        /// <param name="to">待轉出的編碼</param>
        /// <returns></returns>
        public static string ConvertEncode(string str, Encoding from, Encoding to)
        {
            return to.GetString(from.GetBytes(str));
        }

        /// <summary>
        ///  將文件進行md5加密 , md5 值保存在filename.md5 文件中
        /// </summary>
        /// <param name="path">需要加密的文件路徑</param>
        /// <returns>加密的MD5碼</returns>
        public static string getMD5(string path)
        {
            MD5CryptoServiceProvider get_md5 = new MD5CryptoServiceProvider();
            FileStream get_file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            byte[] hash_byte = get_md5.ComputeHash(get_file);
            string result = BitConverter.ToString(hash_byte);
            result = result.Replace("-", "");
            get_file.Close();
            return result;
        }
    }
}
